"use strict";
define(["commonUI","getTime","laydate", "template","global","laydate","select2", "plupload","nav"], function (
    commonUI, getTime,laydate,template,global
) {

    var project = null;
    var user = null;
    var images = [];
    var localUrlMapDBUrl = {}
    var app = {
        init: function () {
            if(!global.existCurrProject()){
                alert("请先选择项目")
                return;
            }
            project = global.getCurrProject();
            user = global.getLoginUser();
            this.initText()
            this.eventBind();
            // getTime.resize();
            getTime.getNowDate();
            getTime.getTimeInfo();
            //初始化运维记录
            app.initTimeline();
            //初始化设备信息
            app.initInfoList();
            //展示保养计划
            app.initMaintainPlan();
        },
        getUrlParam(name) {
            const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            const result = window.location.search.substr(1).match(reg);
            return result ? decodeURIComponent(result[2]) : null;
        },
        /**
        * 渲染文字内容
        */
         initText: function() {
            //用户名显示
            $(".name1").text(user.userName)
        },
        initTimeline: function () {
            var equipmentMaintainId=app.getUrlParam("equipmentMaintainId");
            global.get("/web/om/maintain/equipmentMaintainRecord?equipmentMaintainId="+equipmentMaintainId,response=>{
                var data = response.data.equipmentMaintainRecord;
                $("#maintainNumber").html(data.maintainNumber);
                $("#maintainCount").html(data.maintainCount);

                var data0 = [];
                for(var i=0;i<data.equipmentMaintainRecords.length;i++){
                    var elem = data.equipmentMaintainRecords[i];
                    if(user.roleLevel>=1){
                        data0.push(
                            {
                                rightContent: '<div class="time">'+elem.maintainDate+'<a class="delete-time pull-right del-btn1" id="'+elem.id+'"><i class="aidicon aidicon-delete"></i>删除</a></div>'+
                                '<div class="info-detail"><i class="aidicon aidicon-account"></i><span class="text-label">保养人员：</span><span class="text-info">'+elem.maintainUser+'</span></div>'+
                                '<div class="info-detail"><i class="aidicon aidicon-calendar-text"></i><span class="text-label">作业单号：</span><span class="text-info">'+elem.jobNumber+'</span></div>'+
                                '<div class="info-detail"><i class="aidicon aidicon-brightness-7"></i><span class="text-label">作业内容：</span><span class="text-info">'+elem.jobContent+'</span></div>'
                            }
                        )      
                    }else{
                        data0.push(
                            {
                                rightContent: '<div class="time">'+elem.maintainDate+
                                '<div class="info-detail"><i class="aidicon aidicon-account"></i><span class="text-label">保养人员：</span><span class="text-info">'+elem.maintainUser+'</span></div>'+
                                '<div class="info-detail"><i class="aidicon aidicon-calendar-text"></i><span class="text-label">作业单号：</span><span class="text-info">'+elem.jobNumber+'</span></div>'+
                                '<div class="info-detail"><i class="aidicon aidicon-brightness-7"></i><span class="text-label">作业内容：</span><span class="text-info">'+elem.jobContent+'</span></div>'
                            }
                        )   
                    }           
                }
                var options ={data:data0}
                $('.center-content .record-list').timeline(options)
            });
        },
        initInfoList:function(){
            var equipmentMaintainId=app.getUrlParam("equipmentMaintainId");
            global.get("/web/om/maintain/getEquipmentInfo/"+equipmentMaintainId,response=>{
                var images = response.data.images;
                if(images!=null && images.length>=1){
                    $(".main-img").append('<img src="'+global.baseImageUrl+images[0]+'">');
                    for(var i=1;i<images.length;i++){
                        $(".sub-img").append('<img src="'+global.baseImageUrl+images[i]+'">');
                    }
                }
                var equipmentInfo =response.data.equipmentInfo;
                for(var i=0;i<equipmentInfo.length;i++){
                    var elem = equipmentInfo[i];
                    $(".info-list").append('<li><span class="name">'+elem.name+'</span><span class="value">'+elem.value+'</span></li>')
                    
                }
                
            });
        },
        initMaintainPlan:function(){
            var equipmentMaintainId=app.getUrlParam("equipmentMaintainId");
            global.get("/web/om/maintainPlan/show/"+equipmentMaintainId,response=>{
                var data = response.data;
                for(var i=0;i<data.annualMaintainPlans.length;i++){
                    var elem = data.annualMaintainPlans[i];
                    if(user.roleLevel>=1){
                        $(".annual-plan").append("<tr><td>"+elem.year+"年</td><td width='80%'>"+elem.plan+"</td><td width='100'><a class='delete-td del-btn2' id='"+elem.id+"'>删除</a></td></tr>")
                    }else{
                        $(".annual-plan").append("<tr><td>"+elem.year+"年</td><td width='80%'>"+elem.plan+"</td></tr>")
                    }
                }
                if(data.fiveMaintainPlan!=null){
                    $(".five-plan").html(data.fiveMaintainPlan.plan);
                }
            });
        },
        initUpload: function () {
            // 用于记录上传速度，上传速度过快则加载过程动画无法显示，需要在加载完成方法中进行动画模拟    
            var timer = 0;

            for(var i=0;i<images.length;i++){
                var $img = $('<li class="photoUpload-li"><div class="photoUpload-li-img-wrapper"><img class="photoUpload-li-img" src="'+global.baseImageUrl + images[i]+'"/></div><div class="photoUpload-loading-wrap"><canvas id="photoUpload-loading"></canvas></div><i class="aidicon aidicon-close-circle photoUpload-delete" data-name="'+images[i]+'"></i></li>');
                $img.insertAfter($('#photoUploadMulti8'));
            }
            if($('.photoUpload-li').length>=5) {
                $('#photoUploadMulti8').hide();
            }

            //实例化一个plupload上传对象  
            var uploader8 = new plupload.Uploader({  
                //触发文件选择对话框的按钮，为那个元素id  
                browse_button : 'photoUploadMulti8', 
                multi_selection: false,
                filters: {
                    mime_types : [ 
                        { title : "Image files", extensions : "jpg,png,jpeg" }
                    ],
                },
                //服务器端的上传页面地址  
                url : global.baseImageUrl + "/upload/image"
            });      

            //当文件添加到上传队列后触发  
            uploader8.bind('FilesAdded',function(uploader,files){  
                var img = new moxie.image.Image();
                img.onload = function(){
                    localUrlMapDBUrl[files[0].id]=null;
                    var $img = $('<li class="photoUpload-li" data-id="'+ files[0].id +'"><div class="photoUpload-li-img-wrapper"><img class="photoUpload-li-img" src="'+ this.getAsDataURL()+'"/></div><div class="photoUpload-loading-wrap"><canvas id="photoUpload-loading"></canvas></div><i class="aidicon aidicon-close-circle photoUpload-delete" data-name="'+files[0].id+'"></i></li>');
                    $img.insertAfter($('#photoUploadMulti8'));
                    uploader.start();  
                }
                img.load(files[0].getSource())
                
            });  

            //当队列中的某一个文件上传完成后触发  
            uploader8.bind('FileUploaded',function(uploader,file,response){  
                // 触发上传进度次数太少时,模拟触发上传进度动画
                response = eval('('+response.response + ")")
                if(response.success){
                    images.push(response.data.name);
                    Dialog.toast(response.message, {"intent":"success"});
                }else{
                    Dialog.toast(response.message, {"intent":"warn"});
                    return;
                }
                if(timer < 20){
                    var $dom = $('[data-id="'+ file.id +'"] #photoUpload-loading');
                    var STEP = 5;
                    var animate = function ($dom, percent) {
                        requestAnimationFrame(function () {
                            percent = percent + STEP;
                            uploadImage( $dom,percent);
                            if(percent < 100){
                                animate($dom,percent)
                            }else{
                                // 动画结束隐藏遮罩层
                                $dom.css('display','none');
                            }
                        });
                    };
                    animate($dom,0);
                }else{
                    // 动画结束隐藏遮罩层
                    $dom.css('display','none');
                }
                
                for(var item in localUrlMapDBUrl){
                    if(localUrlMapDBUrl[item]==null){
                        localUrlMapDBUrl[item]=response.data.name
                    }
                }
                console.log(localUrlMapDBUrl)
                console.log("上传成功！");
                if($('.photoUpload-li').length>=5) {
                    $('#photoUploadMulti8').hide();
                }
            });  

            //会在文件上传过程中不断触发，可以用此事件来显示上传进度  
            uploader8.bind('UploadProgress',function(uploader,file){  
                timer++;
                var $dom = $('#progressDemo8 [data-id="'+ file.id +'"] #photoUpload-loading');
                //显示进度
                var percent = file.percent; 
                uploadImage($dom,percent);
            });  

            // 绘制上传进度
            function uploadImage($canvas,percent){
                var c = $canvas[0];
                var ctx = c.getContext('2d');
                var drawCricle = function (ctx, percent) {
                    ctx.beginPath();
                    ctx.moveTo(c.width / 2, c.height / 2);
                    ctx.clearRect(0, 0, c.width, c.height);
                    ctx.arc(c.width / 2, c.width / 2, c.width / 2, Math.PI * 1.5, Math.PI * (1.5 + 2 * percent / 100 ), true);
                    ctx.closePath();
                    ctx.fillStyle = 'rgba(14,16,17,0.4)';
                    ctx.fill();
                };
                drawCricle(ctx, percent, true);
            }

            $(document).on('mouseover','#progressDemo8 .photoUpload-loading-wrap,#progressDemo8 .reUpload,#progressDemo8 .photoUpload-delete',function(e){
                $(this).parent().addClass('photoUpload-active');
            })
            $(document).on('mouseout','#progressDemo8 .photoUpload-loading-wrap,#progressDemo8 .reUpload,#progressDemo8 .photoUpload-delete',function(e){
                $(this).parent().removeClass('photoUpload-active');
            })
            $(document).on('click','#progressDemo8 .photoUpload-delete',function(e){
                var name = $(this).attr("data-name")
                var index = images.indexOf(name)
                if(index!=-1){
                    images.splice(index,1)
                }else{
                    var name = localUrlMapDBUrl[name];
                    index = images.indexOf(name)
                    if(index!=-1){
                        images.splice(index,1)
                    }
                }
                console.log(images)
                $(this).parents('.photoUpload-li').remove();
                $('#photoUploadMulti8').show();
            })

            //在实例对象上调用init()方法进行初始化  
            uploader8.init();
        },
        /** 事件绑定 */
        eventBind: function () {
            // 新增1--添加保养记录
            $(document).on("click", "#add1", function () {
                var equipmentMaintainId = app.getUrlParam("equipmentMaintainId");
                Dialog.open({
                    title: "新增",
                    theme: "formDialog",
                    width: 480,
                    height: 480,
                    context: self,
                    content: template("addFormTpl1"),
                    onShow: function () {
                        laydate.render({
                            elem:'#maintainDate',
                            type:'datetime',
                            eventElem: '.layout-icon-3',
                            trigger: 'click',
                            showBottom: true
                        });
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            var data = {};
                            data.equipmentMaintainId=equipmentMaintainId;
                            data.maintainDate=$("#maintainDate").val();
                            data.maintainUser=$("#maintainUser").val();
                            data.jobNumber=$("#jobNumber").val();
                            data.jobContent=$("#jobContent").val();
                            global.post("/web/om/maintain/addEquipmentMaintainRecord",response=>{
                                if(response.success){
                                    location.reload();
                                }else{
                                    alert(response.message);
                                }
                            },JSON.stringify(data))
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            // 新增2--添加年度保养计划
            $(document).on("click", "#add2", function () {
                var equipmentMaintainId = app.getUrlParam("equipmentMaintainId");
                Dialog.open({
                    title: "添加年度保养计划",
                    theme: "formDialog",
                    width: 480,
                    height: 480,
                    context: self,
                    content: template("addFormTpl2"),
                    onShow: function () {
                        $('#year').select2({
                            //  minimumResultsForSearch设置为-1，去除搜索框 
                            minimumResultsForSearch:-1,
                            placeholder:"请选择",
                            data: [
                                {
                                    id: 2020,
                                    text: '2020'
                                },
                                {
                                    id: 2021,
                                    text: '2021'
                                },{
                                    id: 2022,
                                    text: '2022'
                                },
                                {
                                    id: 2023,
                                    text: '2023'
                                },{
                                    id: 2024,
                                    text: '2024'
                                },
                                {
                                    id: 2025,
                                    text: '2025'
                                },{
                                    id: 2026,
                                    text: '2026'
                                },
                                {
                                    id: 2027,
                                    text: '2027'
                                },{
                                    id: 2028,
                                    text: '2028'
                                },
                                {
                                    id: 2029,
                                    text: '2029'
                                },{
                                    id: 2030,
                                    text: '2030'
                                },
                                {
                                    id: 2031,
                                    text: '2031'
                                },{
                                    id: 2032,
                                    text: '2032'
                                },
                                {
                                    id: 2033,
                                    text: '2033'
                                },{
                                    id: 2034,
                                    text: '2034'
                                },
                                {
                                    id: 2035,
                                    text: '2035'
                                },{
                                    id: 2036,
                                    text: '2036'
                                },
                                {
                                    id: 2037,
                                    text: '2037'
                                },{
                                    id: 2038,
                                    text: '2038'
                                },
                                {
                                    id: 2039,
                                    text: '2039'
                                },{
                                    id: 2040,
                                    text: '2040'
                                },
                                {
                                    id: 2041,
                                    text: '2041'
                                },{
                                    id: 2042,
                                    text: '2042'
                                },
                                {
                                    id: 2043,
                                    text: '2043'
                                },
                                {
                                    id: 2044,
                                    text: '2044'
                                },
                                {
                                    id: 2045,
                                    text: '2045'
                                },
                                {
                                    id: 2046,
                                    text: '2046'
                                },
                                {
                                    id: 2047,
                                    text: '2047'
                                },
                                {
                                    id: 2048,
                                    text: '2048'
                                },
                                {
                                    id: 2049,
                                    text: '2049'
                                },
                                {
                                    id: 2050,
                                    text: '2050'
                                },
                                {
                                    id: 2051,
                                    text: '2051'
                                }
                            ]
                        });
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            var data = {};
                            data.equipmentMaintainId = equipmentMaintainId;
                            data.year = $("#year").val();
                            data.plan = $("#annual-plan").val();
                            global.post("/web/om/maintainPlan/annual/edit",response=>{
                                if(response.success){
                                    location.reload();
                                }else{
                                    alert(response.message);
                                }
                            },JSON.stringify(data))
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            // 编辑1--编辑设备信息
            $(document).on("click", "#edit1", function () {
                var equipmentMaintainId = app.getUrlParam("equipmentMaintainId");
                var data = null;
                global.get("/web/om/maintain/equipmentMaintain/detail/"+equipmentMaintainId,response=>{
                    data = response.data.equipmentMaintain;
                },null,null,false);
                images = data.images;
                console.log(images)
                Dialog.open({
                    title: "编辑运维信息",
                    theme: "formDialog",
                    width: 762,
                    height: 680,
                    context: self,
                    content: template("editFormTpl1",{data:data}),
                    onShow: function () {
                        laydate.render({
                            elem:'#time1',
                            type:'date',
                            eventElem: '.layout-icon-1',
                            trigger: 'click',
                            showBottom: true
                        });
                        laydate.render({
                            elem:'#time2',
                            type:'date',
                            eventElem: '.layout-icon-2',
                            trigger: 'click',
                            showBottom: true
                        });
                        app.initUpload();
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            console.log(images)
                            var data = {}
                            data.equipmentMaintainId=equipmentMaintainId;
                            data.springMaintainDate=$("#time1").val();
                            data.autumnMaintainDate=$("#time2").val();
                            data.description=$("#description").val();
                            data.images=images.join(";");
                            global.post("/web/om/maintain/edit/equipmentMaintain",response=>{
                                if(response.success){
                                    location.reload();
                                }else{
                                    alert(response.message)
                                }
                            },JSON.stringify(data));
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            // 编辑2--编辑五年保养计划
            $(document).on("click", "#edit2", function () {
                var equipmentMaintainId = app.getUrlParam("equipmentMaintainId");
                Dialog.open({
                    title: "编辑五年保养计划",
                    theme: "formDialog",
                    width: 480,
                    height: 480,
                    context: self,
                    content: template("editFormTpl2",{plan:$(".five-plan").html()}),
                    onShow: function () {
                        
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            var data = {}
                            data.id=""
                            data.equipmentMaintainId=equipmentMaintainId;
                            data.plan=$("#fivePlan").val();
                            global.post("/web/om/maintainPlan/five/edit",response=>{
                                if(response.success){
                                    location.reload();
                                }else{
                                    alert(response.message)
                                }
                            },JSON.stringify(data))
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            // 保养状态切换
            $(document).on("click", ".radio-beauty", function (e) {
                if (e.target.nodeName === 'INPUT') {
                    var value = $(this).find('input[type = "radio"]').val()
                    if (value==="1") {
                      $(this).parents('.form-wrap').find('.time-wrap').addClass("hidden")
                    } else {
                        $(this).parents('.form-wrap').find('.time-wrap').removeClass("hidden")
                    }
                }
            })

            $(document).on("click",".del-btn1",function (e) {
                var id = $(this).attr("id");
                //删除运维记录
                global.delete("/web/om/maintain/delEquipmentMaintainRecord?equipmentMaintainRecordId="+id,response=>{
                    if(response.success){
                        Dialog.toast(response.message, {"intent":"success"});
                        location.reload();
                    }else{
                        Dialog.toast(response.message, {"intent":"warn"});
                    }
                })

            })
            $(document).on("click",".del-btn2",function (e) {
                var id = $(this).attr("id");
                //删除年度保养计划
                global.delete("/web/om/maintainPlan/annual/del?annualMaintainPlanId="+id,response=>{
                    if(response.success){
                        Dialog.toast(response.message, {"intent":"success"});
                        location.reload();
                    }else{
                        Dialog.toast(response.message, {"intent":"warn"});
                    }
                })
            })

        }
    };
    return app;
});